package com.worldcup.service.help;

import com.google.common.collect.Lists;
import com.worldcup.model.Travel;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author duwan.zq
 * @date 2018/05/24
 */
@Component
public class CityMatch implements TravelMatch{

    private final static Logger logger = LoggerFactory.getLogger(CityMatch.class);

    private final static String[] SEPARATORS = new String[]{",","，","、", " "};

    private final static double THRESHOLD = 0.5;

    @Override
    public boolean isMatch(List<Travel> travels, List<Travel> refTravels) {
        if(CollectionUtils.isEmpty(travels)){
            return false;
        }
        if(CollectionUtils.isEmpty(refTravels)){
            return false;
        }
        List<String> toCityList = getCityList(travels);
        List<String> refToCityList = getCityList(refTravels);
        for(String city : toCityList){
            city = city.trim();
            for(String refCity : refToCityList){
                refCity = refCity.trim();
                if(com.worldcup.utils.StringUtils.getLevenshteinDistance(city, refCity) >= THRESHOLD){
                    return true;
                }
            }
        }
        return false;
    }

    private List<String> getCityList(List<Travel> travels) {
        List<String> toCityList = new ArrayList<>();
        for(Travel travel : travels){
            String toCity = travel.getToCity();
            toCityList.addAll(splitToCity(toCity));
        }
        return toCityList;
    }

    private List<String> splitToCity(String toCity) {
        if(StringUtils.isBlank(toCity)){
            return Lists.newArrayList();
        }
        for(String separator : SEPARATORS){
            if(toCity.contains(separator)){
                List<String> result = Lists.newArrayList(toCity.split(separator));
                return result;
            }
        }
        return Lists.newArrayList(toCity);
    }


}
